var express = require('express');
var router = express.Router();
var bigkindDAO = require("../bin/db/bigkindDAO.js");
var smallkindDAO = require("../bin/db/smallkindDAO.js");
var goodsDAO = require("../bin/db/goodsDAO.js");
// 请求大类列表名称
router.get("/bigkind", (req, res) => {
    bigkindDAO.find({},{_id:0,img:0,contain:0})
        .then(data => {
            // console.log(data);
            res.json({ data });
        });
});

// 请求具体的某一个大类
router.post("/bigkinditem",(req,res)=>{
    bigkindDAO.findOne({bigkind:req.body.bigkind})
    .populate("contain")
    .then(data=>{
        res.json({data});
    });
});

// 根据小类名称查找某个小类的所有商品
router.get("/itemskindAll",(req,res)=>{
    var greg = new RegExp(req.query.smallkind);
    var condition = {};
    if(req.query.home){
            goodsDAO.find({small:greg})
            .then(data=>{
                res.json({err:0,data:data});
            });
    }
    if(req.query.price){
        if(req.query.asc){
            if(req.query.asc==1){
                condition.newprice = 1;
            }else{
                condition.newprice = -1;
            }
        }
         goodsDAO.find({small:greg})
            .sort(condition)
            .then(data=>{
                res.json({err:0,data:data});
            });
    } 
    if(req.query.num){
        condition.num = -1;
        goodsDAO.find({small:greg})
            .sort(condition)
            .then(data=>{
                res.json({err:0,data:data});
            });
    }
    if(req.query.select){
        if(req.query.lowprice&&req.query.highprice){
            goodsDAO.find({small:greg,newprice:{$gte:req.query.lowprice*1,$lte:req.query.highprice*1}})
            .then(data=>{
                res.json({err:0,data:data});
            });
            
        }else if(req.query.lowprice*1&&!req.query.highprice*1){
            goodsDAO.find({small:greg,newprice:{$gte:req.query.lowprice*1}})
            .then(data=>{
                res.json({err:0,data:data});
            });
        }else if(!req.query.lowprice&&req.query.highprice){
           goodsDAO.find({small:greg,newprice:{$lte:req.query.highprice*1}})
            .then(data=>{
                res.json({err:0,data:data});
            });
        }else{
             goodsDAO.find({small:greg})
            .then(data=>{
                res.json({err:0,data:data});
            });
        }
    }
    // console.log(condition);
   
});



// 根据id查商品详情
router.post("/skindItem",(req,res)=>{
    goodsDAO.findOne(req.body)
    .then(data=>{
        var list = [];
        for(var i=0;i<data.img.length;i++){
            list.push({
                img:'/images/goods/'+data.img[i]
            }); 
        }
        data.img = list;
        // console.log(data);
        res.json({err:0,data:data});
    });
});

//搜索

router.post("/key",(req,res)=>{
    goodsDAO.find({smallkind:req.body.smallkind})
    .then(data=>{
        res.json({err:0,msg:data});
    });
});




module.exports = router;